<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="text" id="input" />
    <script>
      let flag = false;
      // 第一版 利用时间戳
      function throttle(callback,delay){
        let oldTime = 0
        return function (){
           let newTime = Date.now()
          if(newTime - oldTime >= delay){
            callback.apply(this,arguments)
            oldTime = newTime
          }
        }
      }
      // function throttle(callback, delay) {
      //   let timer;
      //   console.log(Date.now());
      //   return function () {
      //     // 为了获取到event事件参数，方便传递参数给下面要执行的参数
      //     let arg = arguments;
      //     if (!timer) {
      //       timer = setTimeout(() => {
      //         timer = null;
      //       }, delay);
      //       callback.apply(this, arg);
      //     }
      //   };
      // }
      function throttle(callback, delay) {
        let timer = null
        return function() {
          if(!timer) {
            timer = setTimeout(() => {
              timer = null
            }, delay)
            callback.apply(this, [...arguments])
          }
        }
      }
      function fn(e) {
        console.log(this);
        console.log(e);
      }
      let input = document.getElementById("input");
      input.onkeyup = throttle(fn, 1000);
    </script>
  </body>
</html>
